package DBLayer;

import ModelLayer.*;
import java.sql.*;
import java.util.ArrayList;

public class DBParent implements DBParentIF
{
	private Connection con;
    
    public DBParent() 
    {
      con = DBConnection.getInstance().getDBcon();
    }
    
    public ArrayList<Parent> getAllParents(boolean retriveAssociation)
    {
        return miscWhere("", retriveAssociation);
    }

    public Parent searchParentID(int ParentID, boolean retriveAssociation)
    {   
    	String wClause = "ParentID = " + ParentID + "";
        return singleWhere(wClause, retriveAssociation);
    }
	
	private ArrayList<Parent> miscWhere(String wClause, boolean retrieveAssociation)
	{
		ResultSet results;
		ArrayList<Parent> ParentList = new ArrayList<Parent>();	
		
		String query =  buildQuery(wClause);
  
  		try
  		{
	 		Statement stmt = con.createStatement();
	 		stmt.setQueryTimeout(5);
	 		results = stmt.executeQuery(query);
	 		
			while( results.next() )
			{
				Parent paObj = new Parent();
				paObj = buildParent(results);
				ParentList.add(paObj);
			}
			stmt.close();
		}
	 	catch(Exception e)
	 	{
	 		System.out.println("Query exception - select: "+e);
			e.printStackTrace();
	 	}
		return ParentList;
	}
	
	private Parent singleWhere(String wClause, boolean retrieveAssociation)
	{
		ResultSet results;
		Parent paObj = new Parent();
	    String query =  buildQuery(wClause);
//        System.out.println(query);
		try
		{
	 		Statement stmt = con.createStatement();
	 		stmt.setQueryTimeout(5);
	 		results = stmt.executeQuery(query);
	 		
	 		if( results.next() )
	 		{
	 			paObj = buildParent(results);
	 			stmt.close();
			}
		}	
	 	catch(Exception e)
	 	{
	 		System.out.println("Query exception: "+e);
	 	}
		return paObj;
	}

	private String buildQuery(String wClause)
	{
	    String query="SELECT * FROM Parent";
		
		if (wClause.length()>0)
			query=query+" WHERE "+ wClause;		
		return query;
	}

	private Parent buildParent(ResultSet results)
      {   
		Parent paObj = new Parent();
          try
          { /* ParentID, workPhone, grownupID */
                paObj.setParentID(results.getInt("ParentID"));
                paObj.setWorkPhone(results.getString("Workphone"));
                paObj.setGrownupID(results.getInt("GrownupID"));
          }
         catch(Exception e)
         {
             System.out.println("error in building the Parent object");
         }
         return paObj;
      }

}
